using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class Sign : MonoBehaviour {

    private PlayerInputController inputControl; // 新输入系统
    private Animator anim;  // 动画控制器
    public GameObject signSprite;   // 可互动标识
    private IInteractable targetItem;
    private bool canPress;  // 当前是否可以按下互动按键
    public Transform playerTrans;   // 玩家的transform

    private void Awake() {
        anim = signSprite.GetComponent<Animator>();
        inputControl = new PlayerInputController(); 
    }

    private void OnEnable() {
        InputSystem.onActionChange += OnActionChange;   // 监听输入操作的状态变化。当输入操作的状态发生改变时，该事件将被触发。
        inputControl.GamePlay.Confirm.started += OnConfirm;
    }

    private void OnDisable() {
        canPress = false;
    }

    private void Start() {
        inputControl.Enable();
    }

    private void Update() {
        signSprite.GetComponent<SpriteRenderer>().enabled = canPress;
        signSprite.transform.localScale = playerTrans.localScale;  // 保证玩家无论朝向哪个方向，互动标识都是正的
    }

    private void OnConfirm(InputAction.CallbackContext callbackContext) {
        if (canPress) {
            targetItem.TriggerAction();
            GetComponent<AudioDefination>().PlayAudioClip();
            canPress = false;
        }
    }

    private void OnActionChange(object obj, InputActionChange actionChange) {
        // 判断当前的输入设备是键盘还是GamePad手柄，然后显示相应的互动标识
        if (actionChange == InputActionChange.ActionStarted) {

            var d = ((InputAction)obj).activeControl.device;  // 当前输入设备

            switch (d.device) {
                case Keyboard:
                    anim.Play("KeyboardE");
                    break;
                case Gamepad:
                    anim.Play("Ps");
                    break;
            }   
            
        }
    }

    private void OnTriggerStay2D(Collider2D other) {
        if (other.CompareTag("Interactable")) {  // 碰到了可互动对象
            canPress = true;
            targetItem = other.GetComponent<IInteractable>();
        }
    }

    private void OnTriggerExit2D(Collider2D other) {
        canPress = false;
    }

}
